package cn.itzzx.lagou.netty.rpc.handler;

import cn.itzzx.lagou.netty.rpc.common.pojo.RpcRequest;
import cn.itzzx.lagou.netty.rpc.provider.UserServiceImpl;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 自定义的业务处理器
 *
 * @author Martin
 * @date 2020-06-17
 * @see 1.0
 */
@Component
public class UserServiceHandler extends ChannelInboundHandlerAdapter implements ApplicationContextAware {

    private static ApplicationContext applicationContext;
    /**
     * 当客户端读取数据时,该方法会被调用
     *
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        RpcRequest rpcRequest = (RpcRequest) msg;
        Class<?> aClass = Class.forName(rpcRequest.getClassName());
        //获取方法对象
        Method method = aClass.getMethod(rpcRequest.getMethodName(), rpcRequest.getParameterTypes());
        //spring管理的bean (根据类型获取bean实例)
        Object bean = applicationContext.getBean(aClass);
        //参数
        Object[] parameters = rpcRequest.getParameters();
        //反射执行
        Object result = method.invoke(bean, parameters);

        //写入结果 直接写入string
        ctx.writeAndFlush(result);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (UserServiceHandler.applicationContext == null) {
            UserServiceHandler.applicationContext = applicationContext;
        }
    }
}
